package netWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25397
 * Date: 2022-04-17
 * Time: 17:27
 */
public class TcpThreadPoolEchoServer {
    private ServerSocket serverSocket=null;


    public TcpThreadPoolEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
            //由于TCP是连续的，不能一上来就读数据，需要先建立连接（接电话）
            //accept就是在“接电话”，接电话的前提是，有人给你打电话，
            //如果当前没有客户端尝试建立连接，此处的accept就会阻塞

            //accept返回了一个socket对象，称为clientSocket，
            //后续和客户端之间沟通，都是通过clientSocket来完成的
            //换句话说，serverSocket就干了一件事，接电话


            //通过线程池实现
            ExecutorService pool= Executors.newCachedThreadPool();
            while(true){
                Socket clientSocket=serverSocket.accept();

                pool.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            processConnection(clientSocket);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端建立连接！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //接下来处理请求和响应
        //这里的针对TCP socket的读写就和文件的读写是一样的
        try(InputStream inputStream= clientSocket.getInputStream()){
            try(OutputStream outputStream=clientSocket.getOutputStream()){
                Scanner scanner=new Scanner(inputStream);
                while(true){//循环处理每个请求
                    //1.读取请求
                    if(!scanner.hasNext()){
                        System.out.printf("[%s:%d] 客户端断开连接\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                        break;
                    }
                    //此处用Scanner更方便，如果不用Scanner就用原生的InputStream的read也是可以的
                    String request= scanner.next();
                    //2.根据请求，计算响应
                    String response=process(request);
                    //3.把这个响应返回给客户端
                    //为了方便，可以使用PrintWriter把OutputStream给包裹一下
                    PrintWriter printWriter=new PrintWriter(outputStream);
                    printWriter.println(response);
                    //刷新缓冲区，如果没有这个刷新，客户端可能就不能第一时间看到响应
                    printWriter.flush();

                    System.out.printf("[%s:%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(),request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpThreadPoolEchoServer server=new TcpThreadPoolEchoServer(1000);
        server.start();
    }
}
